<?php

namespace App\Http\Controllers\Manage;

use App\Http\Controllers\ApiController;
use App\Http\Requests\AuxiliaryStoreRequest;
use App\Http\Requests\AuxiliaryUpdateRequest;
use App\Models\MedicalAuxiliary;
use App\Models\MedicalRecord;
use App\Project\Filters\AuxiliaryFilter;
use App\Project\Transform;
use App\Transformers\MedicalAuxiliaryTransformer;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;

class AuxiliaryController extends ApiController
{
    /**
     * @param \App\Http\Requests\AuxiliaryStoreRequest $request
     * @return mixed
     * @throws \Exception
     * @throws \Throwable
     */
    public function store(AuxiliaryStoreRequest $request)
    {
        //        $input = (new AuxiliaryFilter($request))->input();
        $input = $request->input();

        return \DB::transaction(function () use ($input) {
            $result = MedicalAuxiliary::updateOrCreate(
                ['record_id' => $input['record_id']], $this->convertArrayToJson($input)
            );

            //  将辅助检查的打印选项 数字字符串(例：1,2,3)保存至病历表的 print_auxiliary字段
            if ($printId = $this->getPrintId($input)->implode(',')) {
                MedicalRecord::where(['id' => $input['record_id']])->update(['print_auxiliary' => $printId]);
            }

            return $this->response(['id' => $result['id']]);
        });
    }

    /**
     * 根据输入数据返回需要打印的ID列表
     * @param $input
     * @return \Illuminate\Support\Collection
     */
    protected function getPrintId($input)
    {
        $print = collect($input)->reject(function ($value) {

            if (isset($value['print']))
                return ($value['print'] == 'on') ? false : true;

            return true;
        })->keys()->toArray();

        $printMap = app('field')->get('auxiliary.print');

        return collect($printMap)->pluck('field')->combine(array_keys($printMap))->only($print);
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request)
    {
        $data = null;
        $id   = $request->get('id');

        if ($id > 0) {

            $data = MedicalAuxiliary::findOrFail($id);
        } elseif ($record_id = $request->get('record_id')) {
            $data = MedicalAuxiliary::where(['record_id' => $record_id])->first();
        } else {
            abort(400, '缺失辅助检查ID，或者病历ID');
        }

        if (empty($data)) {
            throw (new ModelNotFoundException())->setModel(MedicalAuxiliary::class);
        }

        return $this->item($data, new MedicalAuxiliaryTransformer());
    }

    /**
     * @param \App\Http\Requests\AuxiliaryUpdateRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function update(AuxiliaryUpdateRequest $request)
    {
        $where = [];

        if ($id = $request->input('id')) {
            $where['id'] = $id;
        } else {
            $where['record_id'] = $request->input('record_id');
        }

        \DB::beginTransaction();

        try {
            //            $input = (new AuxiliaryFilter($request))->except(['id', 'record_id']);

            $input = $request->except(['id', 'record_id']);

            //  将辅助检查的打印选项 数字字符串(例：1,2,3)保存至病历表的 print_auxiliary字段
            $printId = $this->getPrintId($input)->implode(',');

            $input = $this->convertArrayToJson($input);

            $result = MedicalAuxiliary::where($where)->update($input);

            MedicalRecord::where(['id' => $request->input('record_id')])->update(['print_auxiliary' => $printId]);

            \DB::commit();
        } catch (\Exception $e) {

            \DB::rollBack();
            throw $e;
        }

        return $this->responseForUpdate($result);
    }

    public function convertArrayToJson($input)
    {
        return (new Transform())->setArray($input)->convertArrayToJson(
            [
                'blood', 'insulin', 'peptide_c', 'ogtt', 'saccharify', 'diabetes_antibody', 'acr', 'uaer',
                'urine_routine', 'biochemical_examination', 'liver_function', 'kidney', 'electrolyte',
                'tg_chohdlldl', 'bt_paba', 'thyroid_function_one', 'thyroid_function_two', 'thyroid_function_three',
                'plasma_acth', 'blood_cortisol', 'endocrine_examination', 'growth_hormone', 'insulin_growth_factor',
                'blood_routine', 'blood_gas_analysis', 'blood_coagulation_one', 'blood_coagulation_two',
                'dexamethasone_suppression', 'hydroxyvitamin', 'uca_up', 'collagen_degradation', 'iconography'
            ]
        )->get();
    }
}
